#include "ChangeWallPaper.h"
#include <QDateTime>
ChangeWallPaper::ChangeWallPaper(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	connect(&_timer, &QTimer::timeout, this, [this] {
		QString time_str = QDateTime::currentDateTime().toString();
		do_changeWallParper(time_str);
	});
	_timer.start(1000);
}

ChangeWallPaper::~ChangeWallPaper()
{
	//析构时恢复 结果发现被强制结束 压根没机会调用…… 写在main函数里面也一样
	QSettings wallPaper("HKEY_CURRENT_USER\\Control Panel\\Desktop", QSettings::NativeFormat);
	QString last_path;
	if (wallPaper.contains("WallpaperLast"))
	{
		last_path = wallPaper.value("WallpaperLast").toString();
	}
	else {
		last_path = wallPaper.value("Wallpaper").toString();
		wallPaper.setValue("WallpaperLast", last_path);
	}
	//把注册表的桌面图片路径改为指定路径.  
	wallPaper.setValue("Wallpaper", last_path);
	QByteArray byte = last_path.toLocal8Bit();
	//调用windows api.  
	SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, byte.data(), SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}

void ChangeWallPaper::do_changeWallParper(QString text)
{
	QSettings wallPaper("HKEY_CURRENT_USER\\Control Panel\\Desktop", QSettings::NativeFormat);
	QString last_path;
	if (wallPaper.contains("WallpaperLast"))
	{
		last_path = wallPaper.value("WallpaperLast").toString();
	}
	else {
		last_path = wallPaper.value("Wallpaper").toString();
		wallPaper.setValue("WallpaperLast", last_path);
	}

	//生成新的图片
	QPixmap pixmap(last_path);
	QPainter painter(&pixmap);
	//设置线宽和颜色
	QPen pen;
	pen.setWidth(5);
	pen.setColor("red");
	painter.setPen(pen);
	QFont t = painter.font();
	t.setPixelSize(100);
	painter.setFont(t);
	//绘制
	painter.drawText(pixmap.rect(), Qt::AlignCenter, text);

	//另存为
	QFileInfo finfo(last_path);

	QString path = finfo.absolutePath() + "/" + finfo.baseName() + "_new." + finfo.suffix();//那每次都会生成新文件啊 不行，得把它保存下来供下次调用
	pixmap.save(path);
	//把注册表的桌面图片路径改为指定路径.  
	wallPaper.setValue("Wallpaper", path);

	QByteArray byte = path.toLocal8Bit();
	//调用windows api.  
	SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, byte.data(), SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
